#include <algorithm>
#include <iostream>
using namespace std;

const int MAX_N=10000+5;
int sh,sm,eh,em,W,n;
int w[MAX_N],v[MAX_N],c[MAX_N];
int dp[MAX_N];

int main(){
    ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
    char _;
    cin>>sh>>_>>sm>>eh>>_>>em>>n;

    W =  (eh*60+em)-(sh*60+sm);
    // cout<<W<<endl;

    for(int i=1;i<=n;i++){
        cin>>w[i]>>v[i]>>c[i];
    }

    for(int i=1;i<=n;i++){
        if(c[i]==0){
            for(int j=w[i];j<=W;j++){
                dp[j]=max(dp[j],dp[j-w[i]]+v[i]);
            }
        }else{
            for(int j=W;j>=w[i];j--){
                for(int k=1;k*w[i]<=j&&k<=c[i];k++){
                    dp[j]=max(dp[j],dp[j-k*w[i]]+v[i]*k);
                }
            }
        }
    }
    cout<<dp[W]<<endl;
}